<!--
 * @Author: 高瑞寒 15932717091@163.com
 * @Date: 2022-05-18 14:19:55
 * @LastEditTime: 2022-05-20 21:07:03
 * @LastEditors: 高瑞寒 15932717091@163.com
 * @Description:
-->
<!--
 * @Author: 高瑞寒 15932717091@163.com
 * @Date: 2022-05-18 14:19:55
 * @LastEditTime: 2022-05-18 16:18:38
 * @LastEditors: 高瑞寒 15932717091@163.com
 * @Description:
-->
<template>
  <el-dialog
    :model-value="modelValue"
    :title="$t('excel.roleDialogTitle')"
    :before-close="onClose"
  >
    <el-checkbox-group v-model="checkedRoles">
      <el-checkbox
        :label="i.id"
        :key="i.id"
        v-for="i in rolesList"
      >
        {{i.title}}
      </el-checkbox>
    </el-checkbox-group>
    <template #footer>
      <el-button @click="onClose">
        {{$t('universal.cancel')}}
      </el-button>
      <el-button
        type="primary"
        @click="onOk"
      >
        {{$t('universal.confirm')}}
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { getAllRoles } from '@/api/role'
import { getUserDetail, updateUserRoles } from '@/api/user-manager'
import { ElMessage } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { watchSwitchLang } from '@/utils/i18n'
// eslint-disable-next-line no-undef
const props = defineProps({
  modelValue: {
    type: Boolean,
    required: true,
    default: false
  },
  userId: {
    type: String,
    required: true
  }
})
// eslint-disable-next-line no-undef
const emits = defineEmits(['update:modelValue', 'update'])

// 角色列表
const rolesList = ref([])
const getRolesList = async () => {
  rolesList.value = await getAllRoles()
}
getRolesList()
watchSwitchLang(getRolesList)
// 当前用户角色
const checkedRoles = ref([])
const currentUserRole = async () => {
  const { role } = await getUserDetail(props.userId)
  checkedRoles.value = role.map(item => item.id)
}
const i18n = useI18n()
const onOk = async () => {
  /*
    1. map 对选中数组进行遍历
    2. find 遍历全部角色找到匹配项后返回当前项
  */
  const roles = checkedRoles.value.map(curId => {
    return rolesList.value.find(item => item.id === curId)
  })
  await updateUserRoles({ roles }, props.userId)
  emits('update')
  ElMessage.success(i18n.t('role.updateRoleSuccess'))
  onClose()
}
const onClose = () => {
  emits('update:modelValue', false)
}
watch(() => props.userId, (v) => { currentUserRole() })
</script>

<style lang='scss' scoped>
</style>
